<?php
/***************************************************************
 *  Copyright notice
 *
 *  (c) 2008 Julian Kleinhans (jk@web-factory.de)
 *  All rights reserved
 *
 *  Developed for Marketing Factory Consulting GmbH
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *  A copy is found in the textfile GPL.txt and important notices to the license
 *  from the author is found in LICENSE.txt distributed with these scripts.
 *
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

/**
 * tx_cli_import command line interface example
 *
 * The shell call is
 * /www/typo3/cli_dispatch.phpsh EXTKEY TASK
 *
 * real example
 * /www/typo3/cli_dispatch.phpsh user_farm_cli_import import_groups
 * /www/typo3/cli_dispatch.phpsh user_farm_cli_import import_products
 *
 *
 *
 *
 * @author	Marina	Ivanova, mariva@m-design.ru
 * @package TYPO3
 * @subpackage tx_cli_import
 */

//if (!defined('TYPO3_cliMode'))  die('You cannot run this script directly!');
define('PATH_t3lib','../../../../t3lib/');


// Include basis cli class
require_once(PATH_t3lib.'class.t3lib_cli.php');
require_once(PATH_t3lib.'class.t3lib_div.php');


if (!function_exists('mb_ucfirst') && function_exists('mb_substr')) {
	function mb_ucfirst($string) {
		$string = mb_ereg_replace("^[\ ]+","", $string);
		$string = mb_strtoupper(mb_substr($string, 0, 1, "UTF-8"), "UTF-8").mb_substr($string, 1, mb_strlen($string), "UTF-8" );
		return $string;
	}
}

/**
 * Enter description here...
 *
 */
class tx_cli_import extends t3lib_cli {
	var $commerce_cat;


	/**
	 * Constructor
	 *
	 * @return tx_cli_import_cli
	 */
	function tx_cli_import () {
		$this->cli_args['-ss'];
		// Running parent class constructor
		parent::t3lib_cli();

		// Setting help texts:
		$this->cli_help['name'] = 'Prices import';
		$this->cli_help['synopsis'] =  '###OPTIONS###';
		$this->cli_help['description'] = "Class with functionality for insert products groups, prices, rests";
		$this->cli_help['examples'] =  "/.../cli_dispatch.phpsh EXTKEY TASK";
		$this->cli_help['author'] = "mariva@m-design.ru";
		$this->tce = t3lib_div::makeInstance('t3lib_TCEmain');
		setlocale(LC_ALL, "ru_RU.cp1251");
	}
	//
	/**
	* CLI engine
	*
	* @param    array        Command line arguments
	* @return    string
	*/
	function cli_main($argv) {
			
		$this->commerce_cat = $TYPO3_CONF_VARS['EXTCONF']['user_farm_cli_import']['setup']['commerce_cat'];

		$this->commerce_cat_prod = $TYPO3_CONF_VARS['EXTCONF']['user_farm_cli_import']['setup']['commerce_cat_prod'];

			
		// get task (function)
		$task = (string)$this->cli_args['_DEFAULT'][1];

		if (!$task){
			$this->cli_validateArgs();
			$this->cli_help();
			exit;
		}

		set_time_limit(0);
		$this->cli_echo($task);
		switch ($task):
		case 'import_groups':
			$this->import_groups();
			break;
		case 'import_products':
			$this->import_products();
			break;
		case 'import_prices':
			$this->import_prices();
			break;

		default:
			$this->makeFilePhp();
			endswitch;
	}


	function makeFilePhp (){
		$res=mysql_query("SELECT user_farm_commerce_pcode, uid FROM tx_commerce_products WHERE 1");
		$f=fopen("base.php","w");
		fwrite($f,"<? \r\n");
		while ($r=mysql_fetch_assoc($res)){
			fwrite($f,'$ar[\''.$r['user_farm_commerce_pcode'].'\']='.$r['uid'].";\r\n");
		}
		fwrite($f,"echo memory_get_usage(); \r\n ?>");
		fclose ($f);
	}

	function import_prices(){

		$this->cli_echo('
		Start import prices at '.date('dS of F Y h:i:s A
		'));

		$link = $GLOBALS['TYPO3_DB']->link;
			
		$curtime = time();
			
			


		$result = mysql_query('SELECT uid,user_farm_commerce_pcode FROM tx_commerce_products ', $link);
		$product = array();
		while ($row = mysql_fetch_assoc($result)) {

			$product[$row['user_farm_commerce_pcode']] = $row['uid'];
		}

		$res = mysql_query('SELECT name,uid FROM user_farm_branches WHERE deleted=0', $link) ;

		while($branches_row = mysql_fetch_assoc($res))	{

			$filename =  dirname($GLOBALS["temp_path"]).'/fileadmin/import/prices/branch_'.
			$branches_row['uid'].'/'. date('d_m_Y', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y"))).'.csv';
				
			if (file_exists($filename)) {

				$this->cli_echo("\n\n$branches_row[name] - Start import prices at ".date('dS of F Y h:i:s A'));
				$this->cli_echo("\n\n\t\tFor  $branches_row[name] last updated CSV at " . 	date ("F d Y H:i:s.", filemtime($filename)));
					
					
				mysql_query(  'UPDATE `tx_commerce_products`,`user_farm_commerce_product_branch_mm` '.
							'set `user_farm_commerce_price_and_rest`= `user_farm_commerce_price_and_rest`-1 '.
							'WHERE `user_farm_commerce_product_branch_mm`.`product_id`= `tx_commerce_products`.`uid` '.
							'AND `user_farm_commerce_product_branch_mm`.`branch_id`="'.$branches_row['uid'].'"', $link) or die(mysql_error());
					

				mysql_query( 'DELETE FROM `user_farm_commerce_product_branch_mm` WHERE branch_id='.$branches_row['uid'].'', $link)  or die(mysql_error());

					

				$handle = fopen($filename,'r');
				while ((bool)($cat = fgetcsv($handle, 1000, ";")) !== FALSE )

				{

					if (count($cat)!=4) {
						$this->cli_echo("\nWrong csv file format! On string: ".print_r($cat));
						continue;
					}

					if (!empty($product[$cat[0]])) {


						$insdata[] = '(\''.$product[$cat[0]].'\',"'.$branches_row['uid'].'",\''.(float)$cat[1]
						.'\',"'.(float)$cat[2].'","'. (float)$cat[2].'", 106, '.$curtime.', '.$curtime.')';
							
						if (1000<count( $insdata)){


							$iquery = 'INSERT INTO user_farm_commerce_product_branch_mm (product_id,branch_id,branch_price,branch_price_opt,rest, pid,crdate,tstamp ) VALUES '
							. implode(',',$insdata);

							unset($insdata);

							mysql_query('LOCK TABLES user_farm_commerce_product_branch_mm WRITE', $link);

							//mysql_query($iquery, $link) or die($iquery.mysql_error());
							mysql_query('UNLOCK TABLES;', $link);

							unset($iquery);

						}


					}//product exists

				}

				if (isset($insdata)) {


					$iquery = 'INSERT INTO user_farm_commerce_product_branch_mm (product_id,branch_id,branch_price,branch_price_opt,rest, pid,crdate,tstamp ) VALUES '
					. implode(',',$insdata);

					unset($insdata);

					mysql_query('LOCK TABLES user_farm_commerce_product_branch_mm WRITE', $link);

					mysql_query($iquery, $link) or die(mysql_error());
					mysql_query('UNLOCK TABLES;', $link);

					unset($iquery);

						
				}


				mysql_query('UPDATE `tx_commerce_products`,`user_farm_commerce_product_branch_mm` '.
							'set `user_farm_commerce_price_and_rest`= 1+`user_farm_commerce_price_and_rest` '.
							'WHERE `user_farm_commerce_product_branch_mm`.`product_id`= `tx_commerce_products`.`uid` '.
							'AND `user_farm_commerce_product_branch_mm`.`branch_id`="'.$branches_row['uid'].'"', $link) or die(mysql_error());
					

			}//end if for csv-file
			else {
					
				//$this->cli_echo("\n\n$branches_row[name] - Start import prices at ".date('dS of F Y h:i:s A'));
				$this->cli_echo("\n\n\n\t\tFor  $branches_row[name] there is no data to work with in ". $filename);
			}

			$this->cli_echo("\n\n\t\t\t - Finish import prices at ".date('dS of F Y h:i:s A'));

		}///end while for branches
		$s = print_r($this->tce->errorLog,'   ;    ');
		$this->cli_echo($s.'
     Finish import ALL prices at '.date('dS of F Y h:i:s A'));

	}

	function import_products()
	{
		ini_set("memory_limit",'130M');

		$start_time = date('dS of F Y h:i:s A
		');
		$this->cli_echo('
		Start import products at '.date('dS of F Y h:i:s A
		'));


		//$filename = dirname($GLOBALS["temp_path"]).'/fileadmin/import/products/current_products.csv';
		$filename = dirname($GLOBALS["temp_path"]).'/fileadmin/import/products/'.date('d_m_Y', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y"))).'.csv';
		if (file_exists($filename)) {


	 	//$this->cli_echo("Last updated $filename at " . date ("F d Y H:i:s.", filemtime($filename)));
			$this->cli_echo("Last updated CSV at " . date ("F d Y H:i:s.", filemtime($filename)));
			 

			$curtime = time();


			// кешируем страны-производители, компании_производители, категории да и все товары (18мб)
			$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery( 'uid, cn_short_ru',
						 			 'static_countries',
						 			 'cn_short_ru != ""'
						 			 );
						 			 $country = array();
						 			 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
						 			 	$country[$row['cn_short_ru']] = $row['uid'];
						 			 }


						 			 //manuf
						 			 $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
			 				 		 'uid, title',
						 			 'tx_commerce_manufacturer',
									 '1'
									 );
									 $man = array();
									 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
									 	$man[$row['title']] = $row['uid'];
									 }
									 	
									 	
									 $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
			 				 		 'uid,user_farm_commerce_сcode',
						 			 'tx_commerce_categories',
						 			 '1'
						 			 );
						 			 $category = array();
						 			 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
						 			 	$category[$row['user_farm_commerce_сcode']] = $row['uid'];
						 			 }


						 			 $handle = fopen($filename,'r');
						 			 //$f=fopen(dirname($GLOBALS["temp_path"]).'/fileadmin/import/query.txt',"w");

						 			 $link = $GLOBALS['TYPO3_DB']->link;
						 			 
$confArr = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['commerce']);
		$novelty = 86400*(int)$confArr['novelty'];
		//exit;
//novelty
/*
var_dump($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']);*/

/*start dividing DB data*/
/* $result = mysql_query('SELECT count(*) FROM tx_commerce_products', $link);
$parts_results = floor( mysql_num_rows($result)/10000);
var_dump($parts_results);

for ($i = 0; $i <= $parts_results; $i++) { 


						 			 $result = mysql_query('SELECT uid, user_farm_commerce_pcode, crdate FROM tx_commerce_products LIMIT '. 10000*$i .','.(1+$i)*10000, $link);
						 			*/ $product = array();
		$result = mysql_query('SELECT uid, user_farm_commerce_pcode, crdate FROM tx_commerce_products', $link);
						 			 $i=0;
						 			 while ($row = mysql_fetch_assoc($result)) {
						 			 //	echo "\n".$i++;
						 			 //	$product[$row['user_farm_commerce_pcode']]['uid'] = $row['uid'];
						 			 	$product[$row['user_farm_commerce_pcode']] = $row['uid'];
						 			  	$procuct_crdate[$row['user_farm_commerce_pcode']] = $row['crdate'];
						 			 	//$procuct[$row['user_farm_commerce_pcode']]['crdate']= $row['crdate'];
						 			 }
						 			 $qShowStatusResult = mysql_fetch_assoc(mysql_query("SHOW TABLE STATUS LIKE 'tx_commerce_products'"));// or die(mysql_error();

						 			 $next_increment = $qShowStatusResult['Auto_increment'];
						 			
						 			 while (($cat = fgetcsv($handle, 1000, ";")) !== FALSE )
						 			 {


						 			 	if (count($cat)!=10) {
						 			 		$this->cli_echo('Wrong csv file format!
						 			 		On string: '.print_r($cat));
						 			 		exit;
						 			 	}

						 			 	foreach ($cat as &$value) {
						 			 		$value = trim(mb_convert_encoding($value, 'UTF-8','windows-1251'));
						 			 	}
						 			 	 
						 			 		

						 			 	if (!isset($country[$cat[3]])) {
						 			 			
						 			 		mysql_query('INSERT INTO static_countries (cn_short_ru,pid) VALUES ("'.mysql_escape_string($cat[3]).'","0")', $link) or die(mysql_error());
						 			 		$country[$cat[3]] = mysql_insert_id($link);

						 			 	}

						 			 	//manuf

						 			 	if (!isset($man[$cat[4]])) {
						 			 			
						 			 		mysql_query($q = 'INSERT INTO tx_commerce_manufacturer (title,pid,crdate) VALUES ("'.mysql_escape_string($cat[4]).'","105",'.$curtime.')', $link) or die($q.mysql_error());
						 			 		$man[$cat[4]] = mysql_insert_id($link);

						 			 	}



						 			 	if (!isset($product[$cat[1]]['uid'])) {
						 			  	if (isset($category[$cat[8]])){
						 			  			
						 			  		$tdata[] = '\''.
						 			  		mysql_escape_string($cat[0]).'\',"'.
						 			  		$cat[1].'",\''.
						 			  		mysql_escape_string($cat[2]).'\',"'.
						 			  		$country[$cat[3]].'","'.
						 			  		$man[$cat[4]].'",\''.
						 			  		mysql_escape_string(mb_strtolower($cat[5],"UTF-8")).'\',"'.
						 			  		(float)$cat[6].'",\''.
						 			  		mysql_escape_string(mb_strtolower($cat[7],"UTF-8")).'\',"'.
						 			  		$category[$cat[8]].'","'.
						 			  		(('dddd'==mb_strtolower($cat[9],"UTF-8"))?(1):(0)).'"';
						 			  		$cat_num[] = $category[$cat[8]];

						 			  	}
						 			 	 if (1000<count($tdata)){
						 			 	 	//для связи с категориями, до прохода по товарам
						 			 	 	$cnext_increment = $next_increment;
						 			 	 	$query ='';

						 			 	 	foreach ($tdata as $str){
						 			 	 		$query.='(105,'.$curtime.','.$curtime.','.++$next_increment.','.$str.'),';

						 			 	 	}

						 			 	 	unset($tdata);
						 			 	 	$iquery = 'INSERT INTO tx_commerce_products
						 				 	  (pid,crdate,tstamp,uid,user_farm_commerce_article,user_farm_commerce_pcode,title,user_farm_commerce_country_id,
						 				 	  manufacturer_uid,user_farm_commerce_dimension,user_farm_commerce_moscow_price,
						 				 	  user_farm_commerce_wrapper,categories,user_farm_commerce_by_request) 
						 				 	  VALUES '. substr_replace($query, '', -1, 1);
						 			 	 	//	var_dump($iquery);
						 			 	 	unset($query);
						 			 	 	mysql_query('LOCK TABLES tx_commerce_products WRITE', $link);

						 			 	 	mysql_query($iquery, $link) or die(mysql_error());

						 			 	 	mysql_query('UNLOCK TABLES;', $link);
						 			 	 	/*
						 			 	 	 echo $iquery;
						 			 	 	 fwrite($f,$iquery);*/
						 			 	 	unset($iquery);
						 			 	 	//$next_increment = mysql_insert_id($link);//+count($tdata);

						 			 	 	//запомним для следующей итерации
						 			 	 	$cat_query ='';
						 			 	 	foreach ($cat_num as $str){
						 			 	 		$cat_query .= '('.++$cnext_increment.','.$str.',2),';
						 			 	 	}
						 			 	 		
						 			 	 	unset($cat_num);


						 			 	 	$iquery = 'INSERT INTO tx_commerce_products_categories_mm (uid_local,uid_foreign,sorting) VALUES '. substr_replace($cat_query, '', -1, 1);
						 			 	 	unset($cat_query);

						 			 	 	mysql_query('LOCK TABLES tx_commerce_products_categories_mm WRITE', $link);
						 			 	 	mysql_query($iquery, $link) or die(mysql_error());
						 			 	 	mysql_query('UNLOCK TABLES;', $link);

						 			 	 	/*	fwrite($f,$iquery);
						 			 	 	 */
						 			 	 	unset($iquery);


						 			 	 }

						 			 	} /*end insert*/
						 			 	else /*start update */
						 			 	{

						 			 		//	var_dump($product[$cat[1]]);

						 			 		if (isset($category[$cat[8]])){
						 			 			/*	$udata[]=  'UPDATE tx_commerce_products SET user_farm_commerce_article=\''.mysql_escape_string($cat[0]).'\',user_farm_commerce_pcode="'.$cat[1].'",title=\''.mysql_escape_string($cat[2]).'\',user_farm_commerce_country_id="'.$country[$cat[3]].'",manufacturer_uid="'.$man[$cat[4]]
						 			 			 .'",user_farm_commerce_dimension=\''.mysql_escape_string(mb_strtolower($cat[5],"UTF-8")).'\',user_farm_commerce_moscow_price="'.(float)$cat[6].'",
						 			 	  	user_farm_commerce_wrapper=\''.mysql_escape_string(mb_strtolower($cat[7],"UTF-8")).'\',categories="'.$category[$cat[8]].'",
						 			 	  	user_farm_commerce_by_request="'.(('dddd'==mb_strtolower($cat[9],"UTF-8"))?(1):(0)).'" WHERE uid = \''.$product[$cat[1]].'\'; ';

						 			 	  	$ucat_num[] = 'UPDATE tx_commerce_products_categories_mm SET uid_foreign=\''. $category[$cat[8]].'\' WHERE uid_local = \''.$product[$cat[1]].'\'; ';
						 			 				*/
						 			 				



						 			 			$udata[]=  '(105,"'.$procuct_crdate[$cat[1]].'",'.$curtime.',\''.$product[$cat[1]].'\',\''.mysql_escape_string($cat[0]).'\',"'.$cat[1].'",\''.mysql_escape_string($cat[2]).'\',"'.$country[$cat[3]].'","'.$man[$cat[4]]
						 			 	 	.'",\''.mysql_escape_string(mb_strtolower($cat[5],"UTF-8")).'\',"'.(float)$cat[6].'",
						 			 	  	\''.mysql_escape_string(mb_strtolower($cat[7],"UTF-8")).'\',"'.$category[$cat[8]].'",
 			 								"'.(('dddd'==mb_strtolower($cat[9],"UTF-8"))?(1):(0)).'")';


						 			 	 	$ucat_num[] = '(\''. $category[$cat[8]].'\',\''.$product[$cat[1]]['uid'].'\')';
						 			 		}

						 			 	 if (1000<count($udata)){
						 			 	 		
						 			 	 		
						 			 	 	mysql_query('LOCK TABLES tx_commerce_products,tx_commerce_products_categories_mm WRITE', $link);

						 			 	 	mysql_query($q = 'REPLACE INTO tx_commerce_products (pid,crdate,tstamp,uid,user_farm_commerce_article,user_farm_commerce_pcode,title,user_farm_commerce_country_id,manufacturer_uid
						 			 		,user_farm_commerce_dimension,user_farm_commerce_moscow_price,
						 			 	  	user_farm_commerce_wrapper,categories,
 			 								user_farm_commerce_by_request) VALUES '. implode(',', $udata), $link) or die(mysql_error());
 
						 			 	 	mysql_query($q='REPLACE INTO tx_commerce_products_categories_mm (uid_foreign,uid_local) VALUES '.implode(',',$ucat_num), $link) or die(mysql_error());
						 			 	 	mysql_query('UNLOCK TABLES;', $link);



						 			 	 	unset($udata);
						 			 	 	unset($ucat_num);

						 			 	 }
						 			 	}

						 			 	unset($cat);


						 			 }//end while
						 			 
						 			 unset($product);
						 			   	unset($procuct_crdate);
						 			 rewind($handle);
						 			// } /*end dividing DB data*/
						 			 
						 			 if(isset($tdata))
						 			 {
						 			 	//для связи с категориями, до прохода по товарам
						 			 	$cnext_increment = $next_increment;
						 			 	$query ='';

						 			 	foreach ($tdata as $str){
						 			 		$query.='(105,'.$curtime.','.$curtime.','.++$next_increment.','.$str.'),';

						 			 	}

						 			 	unset($tdata);
						 			 	$iquery = 'INSERT INTO tx_commerce_products
						 				 	  (pid,crdate,tstamp,uid,user_farm_commerce_article,user_farm_commerce_pcode,title,user_farm_commerce_country_id,
						 				 	  manufacturer_uid,user_farm_commerce_dimension,user_farm_commerce_moscow_price,
						 				 	  user_farm_commerce_wrapper,categories,user_farm_commerce_by_request) 
						 				 	  VALUES '. substr_replace($query, '', -1, 1);
						 			 	//	var_dump($iquery);
						 			 	unset($query);
						 			 	mysql_query('LOCK TABLES tx_commerce_products WRITE', $link);

						 			 	mysql_query($iquery, $link) or die(mysql_error());

						 			 	mysql_query('UNLOCK TABLES;', $link);
						 			 	 
						 			 	unset($iquery);
						 			 	//$next_increment = mysql_insert_id($link);//+count($tdata);

						 			 	//запомним для следующей итерации
						 			 	$cat_query ='';
						 			 	foreach ($cat_num as $str){
						 			 		$cat_query .= '('.++$cnext_increment.','.$str.',2),';
						 			 	}
						 			 		
						 			 	unset($cat_num);


						 			 	$iquery = 'INSERT INTO tx_commerce_products_categories_mm (uid_local,uid_foreign,sorting) VALUES '. substr_replace($cat_query, '', -1, 1);
						 			 	unset($cat_query);

						 			 	mysql_query('LOCK TABLES tx_commerce_products_categories_mm WRITE', $link);
						 			 	mysql_query($iquery, $link) or die(mysql_error());
						 			 	mysql_query('UNLOCK TABLES;', $link);

						 			 	/*	fwrite($f,$iquery);
						 			 	 */
						 			 	unset($iquery);


						 			 }
						 			 if(isset($udata)){
						 			 		
						 			 		
						 			 	mysql_query('LOCK TABLES tx_commerce_products,tx_commerce_products_categories_mm WRITE', $link);

						 			 	mysql_query('REPLACE INTO tx_commerce_products (pid,crdate,tstamp,uid,user_farm_commerce_article,user_farm_commerce_pcode,title,user_farm_commerce_country_id,manufacturer_uid
						 			 		,user_farm_commerce_dimension,user_farm_commerce_moscow_price,
						 			 	  	user_farm_commerce_wrapper,categories,
 			 								user_farm_commerce_by_request) VALUES '. implode(',', $udata), $link) or die(mysql_error());

						 			 	mysql_query($q='REPLACE INTO tx_commerce_products_categories_mm (uid_foreign,uid_local) VALUES '.implode(',',$ucat_num), $link) or die(mysql_error());
						 			 	mysql_query('UNLOCK TABLES;', $link);



						 			 	unset($udata);
						 			 	unset($ucat_num);

						 			 	 
						 			 }
						 			 
						 			  fclose ($handle);
						 			  
		}
		else
		{$this->cli_echo('
		There is no data to work with in '. $filename.'
		');
		exit;
		}
		$s = print_r($this->tce->errorLog,'   ;    ');
		$this->cli_echo($s.'
     Finish import products at '.date('dS of F Y h:i:s A'));
			

	}
	/**
	 * myFunction which is called over cli
	 *
	 */

	function import_groups() {
		$this->cli_echo('
		Start import groups at '.date('dS of F Y h:i:s A'));
		//var_dump(dirname($GLOBALS["temp_path"]));
		// 'www'.$_SERVER['HOST'].
		//$filename =   dirname($GLOBALS["temp_path"]).'/fileadmin/import/categories/current_categories.csv';
		$filename =   dirname($GLOBALS["temp_path"]).'/fileadmin/import/categories/'. date('d_m_Y', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y"))).'.csv';
			
		if (file_exists($filename)) {

			$childs=array();
	 	//$this->cli_echo("Last updated $filename at " . date ("F d Y H:i:s.", filemtime($filename)));
	 	$this->cli_echo("\nLast updated CSV at " . date ("F d Y H:i:s.", filemtime($filename)));
	 	/**/
		 
		// create the parent category if it not exists
		$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
			'uid',
			'tx_commerce_categories',
			'uname=\'PARENT\' AND parent_category=\'\' AND deleted=0'
		);
		$parentCatUid = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
		$parentCatUid = (int)$parentCatUid['uid'];
		 
		if (!$res || intval($parentCatUid) == 0) {
			mysql_query('REPLACE INTO tx_commerce_categories (uid,pid,title,uname,parent_category) VALUES (1,106,"Каталог продукции","PARENT","")') or die($q.mysql_error());
		
		$parentCatUid = 1;
		
/*	
			$catArray = $addArray;
			$catArray['title'] = 'Каталог продукции';
			$catArray['pid'] = 106;
			$catArray['uname'] = 'PARENT';
			$GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_commerce_categories', $catArray); 
			$parentCatUid =  $GLOBALS['TYPO3_DB']->sql_insert_id();*/
			
		}
		/**/
		var_dump($parentCatUid);// exit();
		
	 	$handle = fopen($filename,'r');
			/*
			 $data=file($filename, FILE_IGNORE_NEW_LINES);
			 foreach ($data as $line)
			 	
			 function iem($a){
				return empty($a);
				}
				while (!iem($cat = fgetcsv($handle, 1000, ";")))

				* //	$cat=explode(';',$line);*/

	 	while (($cat = fgetcsv($handle, 1000, ";")) !== FALSE )
			{

				if (count($cat)!=2) {
					$this->cli_echo('Wrong csv file format!');
					$this->cli_echo('\nOn string '.print_r($cat));
					exit;
				}
				$is_frst_level=0;
				$cat[1] = rtrim($cat[1]);
				$cat[1] = mb_convert_encoding($cat[1], 'UTF-8','windows-1251');
				$cat[0] = mb_convert_encoding($cat[0], 'UTF-8','windows-1251');

				preg_match("/^([A-ZА-Я]{1,2})([0]{3,4})$/u", $cat[0],$parts1);		
				preg_match("/^[^\wа-я]+$/u",$cat[1],$parts2);

				if (!empty($parts1)||(!empty($parts2)) )  {

					$is_frst_level=1;
					$pccode = ((!empty($parts1[1]))?($parts1[1]):($cat[0]));


				}

				/*	$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
				 'uid',
				 'tx_commerce_categories',
				 'user_farm_commerce_сcode = "'.$cat[0].'"'
				 );
				 */

				list($id)=mysql_fetch_array($GLOBALS['TYPO3_DB']->sql($TYPO3_DB,
					"SELECT uid FROM tx_commerce_categories WHERE user_farm_commerce_сcode = '{$cat[0]}'"));
				//	echo "\r\n $q -{$cat[0]}- $id-";
					
				///	 die(mysql_error());



				if ($id){

					//$curr = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
					$tdata['tx_commerce_categories'][$id] = array("title" =>   $cat[1]);
					
					/*	$tdata['tx_commerce_categories'][$id] = array(

  									  "user_farm_commerce_сcode" => $cat[0],
							
    								  "parent_category" => $parentCatUid,

    								  "title" => $cat[1],// mb_ucfirst(mb_strtolower($cat[1])),//
							
    								  "pid" =>  106//$this->commerce_cat 

						);*/

					//echo ucfirst(strtolower($cat[1]));

					if (1==$is_frst_level)		$correl_code[$pccode]= $id;

				}
				else
				{ //такой категории еще нет. выясним ее родителя

					if (1==$is_frst_level){
							
						$tce_key =  str_pad( 'NEW', 10, md5(uniqid(rand(), true)));

						$tdata['tx_commerce_categories'][$tce_key] = array(

  									  "user_farm_commerce_сcode" => $cat[0],
							
    								  //"parent_category" =>  $parentCatUid,

    								  "title" =>  $cat[1],//
							
    								  "pid" =>  106//$this->commerce_cat 

						);
						
//var_dump($tdata['tx_commerce_categories'][$tce_key]);
						$correl_code[$pccode] = $tce_key;
							
					}
					else {

						$childs[] = $cat;
							
					}
				};
					

			}
			
			
			$this->tce->start($tdata,array());
			//var_dump($tdata);
			$this->tce->process_datamap();
			$s = print_r($this->tce->errorLog,'   ;    ');
			$tce_new = $this->tce->substNEWwithIDs;
			$key_lenth=array();
			
			
		
			
		 
		 
			foreach ($childs as $sub_cat){

				foreach ($correl_code as $pccode=>$pcat_key)
				{
					$matches = !strncasecmp  ( $sub_cat[0] , $pccode  , strlen($pccode) );
					//key
					if ($matches)
					if ( (int)$key_lenth[$sub_cat[0]] < strlen($pcat_key))
					{
						$contiguity[ $sub_cat[0] ]= $pcat_key;

						$key_lenth[$sub_cat[0]] = strlen($pcat_key);

						/*		echo  '
						 for code '.$sub_cat[0].' parent is '.$pccode.' with'.$pcat_key;*/
					}
				}


					
				$tce_key =  str_pad( 'NEW', 10, md5(uniqid(rand(), true)));

				$cdata['tx_commerce_categories'][$tce_key] = array(

	 								  "title" => $sub_cat[1],

  									  "user_farm_commerce_сcode" => $sub_cat[0],
					
    								  "parent_category" =>  $tce_new[ $contiguity[ $sub_cat[0] ]] ,
					
    								  "pid" => 106// $this->commerce_cat 

				);
			}
			echo "\nChild tx_commerce_categories = ".count($cdata['tx_commerce_categories']);
			//file_put_contents("tce.txt",var_export($tdata,true));
			//	file_put_contents("cce.txt",var_export($cdata,true));
	  	$this->tce->start($cdata,array());
	  	//var_dump($cdata);

 	 	 	$this->tce->process_datamap();

	 	$s = print_r($this->tce->errorLog,'   ;    ');
	 	 
		/*	foreach ($tdata['tx_commerce_categories'] as $k=>$v){
		// mysql_query($q="UPDATE tx_commerce_categories SET title='{$v['title']}', parent_category=$parentCatUid WHERE user_farm_commerce_сcode = '{$v['user_farm_commerce_сcode']}' ");	
			//echo "$q";
			}*/
	 
		}
		else { $this->cli_echo('
		There is no data to work with in  "/fileadmin/import/categories/'. date('d_m_Y', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y"))).'.csv"');
		}
		
			$this->cli_echo($s.'
     Finish import groups at '.date('dS of F Y h:i:s A')); 
			
	}

}

// Call the functionality
$cleanerObj = t3lib_div::makeInstance('tx_cli_import');
$cleanerObj->cli_main($_SERVER['argv']);

?>
